$NG.AllReady(function (page, { useValuesChange, useUpdateRow, useUpdateRows, useBeforeClick }) {
    // 获取控件
    const form = $NG.getCmpApi("p_form_equipment_list_split");
    const grid = $NG.getCmpApi("p_form_equipment_split_d");
    const grid2 = $NG.getCmpApi("p_form_equipment_split_dd");
  
    const dataMaps_key = {};
  
    ////////////////////////////////////////////////////////////--form--////////////////////////////////////////////////////////////
    ////////////////////////////////////////////////////////////--form--////////////////////////////////////////////////////////////
    ////////////////////////////////////////////////////////////--form--////////////////////////////////////////////////////////////
    if (form) {
      form.getItem("bill_name").setValue(form.getItem("phid_pc").getText() + "采购合同");
      useValuesChange(({ args }) => {
        form.getItem("bill_name").setValue(form.getItem("phid_pc").getText() + "采购合同");
      }, "p_form_equipment_list_split.phid_pc");
    }
  
    useBeforeClick(async ({ args }) => {
      let lock = true;
      const _data = grid.getRows();
      const dataMap = {};
      const errArr = [];
      _data.forEach((item) => {
        console.log(item);
        dataMap[item.u_cnt_d_no] ? (dataMap[item.u_cnt_d_no] += Number(item.u_qty) || 0) : (dataMap[item.u_cnt_d_no] = Number(item.u_qty) || 0);
      });
      for (let key in dataMap) {
        window._lsz_catch_cntDetial.forEach((elem) => {
          if (key == elem.item_no && dataMap[key] > elem.qty) {
            lock = false;
            errArr.push(key);
          }
        });
      }
      console.log(lock, dataMap);
      if (!lock) {
        $NG.alert(`部分合同编码明细数量超出合同数量<<<< ${errArr} >>>>`);
      }
      return lock;
    }, "save");
  
    if (form) {
      //切分公司和切分主体的过滤条件
      $NG.updateUI((updater) => {
        const fields = ["u_split_performer", "u_split_org"];
        fields.forEach((field) => {
          // $NG.getPageUI(); 根据组件目录设置路径，可能存在 PCFieldSetPanelGroup[i][field]
          updater.form.p_form_equipment_list_split[field].setProps({
            // hidden: false, //隐藏
            // required: true, //必输
            // disabled: true, //只读
            // clientSqlFilter: `compno in ('1','2','3','4')`, //过滤条件
            // placeholder: "请选择", //输入框字段加提示语
          });
        });
      });
    }
  
    // 监听表头 `u_split_rate` 变化
    useValuesChange(({ args }) => {
      console.log("useValuesChange is ready", args[0]);
  
      const u_split_rate = form.getItem("u_split_rate").getValue();
      const data = grid.getData().map((item) => ({ ...item, u_split_rate }));
  
      data.forEach(sum);
  
      grid.clearRows().then(() => grid.addRows(data));
      caculatedgrid();
    }, "p_form_equipment_list_split.u_split_rate");
    useValuesChange(({ args }) => {
      getSupplyFromCnt();
      getCntDetialByPhid();
      getCntCount();
    }, "p_form_equipment_list_split.phid_pc");
    getCntCount();
    function getCntCount() {
      if (!form.getItem("phid_pc").getValue()) return;
      $NG.execServer("getCntCount", { type: 1, phid_pc: form.getItem("phid_pc").getValue() }, (res) => {
        console.log(`合同数量`, res.count);
        window._lsz_catch_cntCount = res.count;
      });
    }
    // 隐藏 grid1 按钮
    const gridToolbar = $NG.getCmpApi("toolbar_p_form_equipment_split_d");
    gridToolbar.getItem("imp").setProps({ children: "引用设备清单明细" });
    ["attachment", "addrow"].forEach((btn) => gridToolbar.hideButton(btn));
  
    useUpdateRow(caculatedgrid, "p_form_equipment_split_d");
  
    useUpdateRows(({ args }) => {
      console.log(`表格新增监听`, args);
      // setSpiltAmt();
      // caculatedgrid();
      reduceSum();
      updateGrid2FromGrid();
      // setCntDetial();
      const rows = args[0];
      rows.forEach((items, index) => {
        // 根据合同清单ID获取合同清单的单价getCntDInfoByPhid
        $NG.execServer("getCntDInfo", { phid: items.u_cnt_d_id }, function (res) {
          if (res.count > 0) {
            var data = JSON.parse(res.data)[0].extendObjects; //单返回值
            // record.u_cnt_item_no = data.item_no; //合同清单编码
            // record.u_spec = data.user_ggxh; //规格型号
            // record.u_msunit = data.unit_phid;
            // record.u_msunit_EXName = data.unit_name; //计量单位
            // record.u_tech_params = data.user_jscs; //技术参数
            // record.u_brand = data.brand_phid;
            // record.u_brand_EXName = data.brand_name; //品牌
            // record.u_pc_subitem_category = data.user_gcfxfl; //工程分项分类
            items.u_cnt_d_qty = data.qty; //合同清单数量
            // record.u_cnt_item_tax_rate = data.taxrate; //税率
            items.u_ori_prc_vat = data.prc_vat_fc; //含税单价
            items.u_ori_prc = data.prc_fc; //未税单价
            items.u_ori_amt_vat = data.amt_vat_fc; //含税金额
            items.u_ori_amt = data.amt_fc; //未税金额
          } else {
            console.log(items.u_cnt_d_id + "没有找到合同清单");
          }
        });
      });
      grid.refreshView();
    }, "p_form_equipment_split_d");
  
    // 隐藏 grid2 按钮
    const grid2Toolbar = $NG.getCmpApi("toolbar_p_form_equipment_split_dd");
    ["imp", "addrow", "deleterow", "attachment"].forEach((btn) => grid2Toolbar.hideButton(btn));
  
    useUpdateRows(() => {
      setSpiltAmt();
      reduceSum();
    }, "p_form_equipment_split_dd");
  
    setInterval(() => {
      try {
        const currentLength = grid.getData().length;
        if (currentLength !== dataMaps_key["danjv"]) {
          dataMaps_key["danjv"] = currentLength;
          grid.getData().forEach(sum);
          caculatedgrid();
          console.log("可能发生了单据引用");
        }
      } catch (err) {}
    }, 500);
    /** 监听 grid 数据变化，并同步更新 grid2 */
    function updateGrid2FromGrid() {
      let gridRows = grid.getRows();
      let revenueTypeMap = new Map(gridRows.map((item) => [item.u_revenue_type, item.u_revenue_type_EXName]));
        console.log(`查看明细`,revenueTypeMap);
      let grid2Rows = grid2.getRows();
      let grid2Types = new Set(grid2Rows.map((item) => item.u_revenue_type));
        console.log(`查看去重类型明细`,grid2Types);
      const _arr = [];
      // **新增行**
      revenueTypeMap.forEach((name, type) => {
        if (!grid2Types.has(type)&&type) {
          _arr.push({ u_revenue_type: type, u_revenue_type_EXName: name });
          console.log(`已添加 ${type}（${name}）到 grid2`);
        }
      });
      //改变地址避免影响
      grid2.addRows([..._arr]);
  
      // **删除行**
      grid2Rows.forEach((item) => {
        if (!revenueTypeMap.has(item.u_revenue_type)) {
          grid2.deleteRow(item);
          console.log(`已删除 ${item.u_revenue_type}（${item.u_revenue_type_EXName}）`);
        }
      });
      grid2.refreshView();
    }
    setInterval(() => {
      // console.log(grid2.getRows());
    }, 2000);
    /** 设置切分比例 */
    function setSpiltAmt() {
      grid.getRows().forEach((item) => {
        selectClass(item.u_revenue_type, (data) => {
          if (data) {
            item.u_split_rate = data.u_split_rate;
            sum(item);
            grid.refreshView();
          }
        });
      });
    }
  
    /** 查询切分比例 */
    function selectClass(phid, callback) {
      const result = grid2.getRows().find((item) => item.u_revenue_type == phid) || {};
      console.log("查询切分成功", result);
      callback(result);
    }
    getSupplyFromCnt();
    function getSupplyFromCnt() {
      const phidPc = form.getItem("phid_pc").getValue();
      if (!phidPc) return;
      $NG.execServer("getSupplyFromCnt", { phid_pc: phidPc }, (res) => {
        console.log(res);
        const _arr = [];
        if (res.count == 0) return;
        const _data = JSON.parse(res.data);
        console.log(_data);
        _data.forEach((items) => {
          const item = items.extendObjects;
          _arr.push(item.supply_id);
        });
        let str = _arr.reduce((value, item, index) => {
          if (index == 0) {
            return `${value}'${item}'`;
          }
          return `${value},'${item}'`;
        }, "(");
        str += ")";
        console.log(str, `fe.phid in ${str}`);
        $NG.updateUI((updater) => {
          console.log(updater);
          // $NG.getPageUI(); 根据组件目录设置路径，可能存在 PCFieldSetPanelGroup[i][field]
          updater.form.p_form_equipment_list_split.u_split_performer.setProps({
            // hidden: false, //隐藏
            // required: true, //必输
            // disabled: true, //只读
            clientSqlFilter: `fe.phid in ${str}`, //过滤条件
            // placeholder: "请选择", //输入框字段加提示语
          });
        });
      });
    }
    // setInterval(() => {
    //   try {
    //     const currentLength = grid.getData().length;
    //     if (currentLength !== dataMaps_key["danjv"]) {
    //       dataMaps_key["danjv"] = currentLength;
    //       grid.getData().forEach(sum);
    //       caculatedgrid();
    //       console.log("可能发生了单据引用");
    //     }
    //   } catch (err) {}
    // }, 500);
  
    /** 计算 grid1 总计金额 */
    function caculatedgrid() {
      let sum_amt_vat = 0,
        sum_amt = 0;
  
      grid.getRows().forEach(({ u_split_amt_vat = 0, u_split_amt = 0 }) => {
        sum_amt_vat += parseFloat(u_split_amt_vat);
        sum_amt += parseFloat(u_split_amt);
      });
  
      $NG.updateState((updater) => {
        updater.data.p_form_equipment_list_split.setProps({ u_split_amt_vat: sum_amt_vat, u_split_amt: sum_amt });
      });
    }
  
    /** 计算每行数据 */
    function sum(item) {
      const taxRate = Number(item.u_tax_rate) || 0;
      const qty = Number(item.u_qty) || 0;
      const oriPrcVat = Number(item.u_ori_prc_vat) || 0;
      const splitRate = Number(item.u_split_rate) || 0;
  
      item.u_ori_prc = oriPrcVat / (1 + taxRate);
      item.u_split_prc_vat = oriPrcVat * splitRate;
      item.u_split_prc = item.u_split_prc_vat / (1 + taxRate);
      item.u_split_amt_vat = qty * item.u_split_prc_vat;
      item.u_split_amt = qty * item.u_split_prc;
      item.u_tax_amt = item.u_split_amt * taxRate;
  
      grid.refreshView();
    }
  
    /** 汇总含税金额 */
    function reduceSum() {
      const summary = grid.getRows().reduce((acc, item) => {
        if (!acc[item.u_revenue_type]) {
          acc[item.u_revenue_type] = { u_split_amt_vat: 0, u_split_amt: 0, u_tax_amt: 0 };
        }
        acc[item.u_revenue_type].u_split_amt_vat += Number(item.u_split_amt_vat) || 0;
        acc[item.u_revenue_type].u_split_amt += Number(item.u_split_amt) || 0;
        acc[item.u_revenue_type].u_tax_amt += Number(item.u_tax_amt) || 0;
        return acc;
      }, {});
  
      grid2.getRows().forEach((item) => {
        const data = summary[item.u_revenue_type] || { u_split_amt_vat: 0, u_split_amt: 0, u_tax_amt: 0 };
        Object.assign(item, data);
      });
  
      console.log(`金额`, summary);
      grid2.refreshView();
    }
  
    function setCntDetial() {
      //   const grid_data = grid.getRows();
      //   if (!window._lsz_catch_cntDetial) return;
      //   grid_data.forEach((item) => {
      //     window._lsz_catch_cntDetial.forEach((elem) => {
      //       if (item.u_cnt_d_no == elem.item_no && item._init) {
      //         item.u_qty = elem.qty;
      //         item.u_tax_rate = elem.taxrate;
      //         item.u_ori_prc_vat = elem.prc_vat_fc;
      //         item.u_ori_prc = elem.prc_fc;
      //         item.u_ori_amt_vat = elem.amt_vat_fc;
      //         item.u_ori_amt = elem.amt_fc;
      //         item._init = true;
      //       }
      //     });
      //   });
      //   grid.refreshView();
    }
    getCntDetialByPhid();
    function getCntDetialByPhid() {
      const phidPc = form.getItem("phid_pc").getValue();
      if (!phidPc) return;
      $NG.execServer("getCntDetialByPhid", { phid_pc: phidPc }, (res) => {
        if (res.count == 0) return;
        const _data = JSON.parse(res.data);
        console.log(_data);
        const _temp = [];
        _data.forEach((item) => {
          const data = item.extendObjects;
          _temp.push(data);
        });
        window._lsz_catch_cntDetial = [..._temp];
      });
    }
  });
  